<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <!--
        <el-form-item prop="approveId" label="审批流程ID">
          <el-input v-model="listQuery.approveId" placeholder="审批流程ID" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="approveOrderCode" label="审批单编号">
          <InputTagDialog v-model="listQuery.approveOrderCode" placeholder="审批单编号" title="填写审批单编号" />
        </el-form-item>
        <el-form-item prop="approveOrderName" label="审批单名称">
          <el-input v-model="listQuery.approveOrderName" placeholder="审批单名称"/>
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('ApproveOrderState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="submitUserId" label="提交人">
          <User v-model="listQuery.submitUserId" keyName="id" keyShow="name" placeholder="提交人" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="approveResult" label="审批结果">
          <el-radio-group v-model="listQuery.approveResult">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('ApproveResult')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="businessType" label="业务单类型">
          <el-select v-model="listQuery.businessType" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getEnumList('ApproveOrderBusinessType')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('PD0049')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="审批模版名称" prop="approveId" min-width="190px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="approveList" :foreignIds="row.approveId" :foreignLabel="'approveName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="审批单编号" prop="approveOrderCode" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.approveOrderCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="审批单名称" prop="approveOrderName" min-width="200px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.approveOrderName }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveOrderState')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="提交人用户" prop="submitUserId" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.submitUserId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="当前审批节点号" prop="submitUserId" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.currentNo }}</template>
      </el-table-column>
      <el-table-column align="center" label="当前审批组织架构" prop="currentApproveOrgId" min-width="230px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <LabelTag :foreignList="organizationList" :foreignIds="row.currentApproveOrgId" :foreignLabel="'organizationName'" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="当前审批人角色" prop="currentApproveRoleId" min-width="230px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <LabelTag :foreignList="roleList" :foreignIds="row.currentApproveRoleId" :foreignLabel="'roleName'" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="当前审批人用户" prop="currentApproveUserId" min-width="230px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <LabelTag :foreignList="userList" :foreignIds="row.currentApproveUserId" :foreignLabel="'name'" />
        </template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="下一节点审批组织架构" prop="nextApproveOrgId" min-width="280px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.nextApproveOrgId === '-1' ? '无' : showIdLabel(organizationList, row.nextApproveOrgId, 'organizationName') }}</template>
      </el-table-column>
      <el-table-column align="center" label="下一节点审批角色" prop="nextApproveRoleId" min-width="280px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.nextApproveRoleId === '-1' ? '无' : showIdLabel(roleList, row.nextApproveRoleId, 'organizationName') }}</template>
      </el-table-column>
      <el-table-column align="center" label="下一节点审批人用户" prop="nextApproveUserId" min-width="280px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.nextApproveUserId === '-1' ? '无' : showIdLabel(userList, row.nextApproveUserId, 'name') }}</template>
      </el-table-column>
      -->
      <el-table-column align="center" label="审批结果" prop="approveResult" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveResult')" :enum-key="row.approveResult" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="审批意见" prop="approveOpinion" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.approveOpinion }}</template>
      </el-table-column>
      <el-table-column align="center" label="业务单类型" prop="businessType" min-width="200px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveOrderBusinessType')" :enum-key="row.businessType" />
        </template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="业务单ID" prop="businessId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.businessId }}</template>
      </el-table-column>
      <el-table-column align="center" label="业务单详情URL" prop="businessUrl" min-width="205px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.businessUrl }}</template>
      </el-table-column>
      <el-table-column align="center" label="业务处理BeanClass" prop="businessClass" min-width="330px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.businessClass }}</template>
      </el-table-column>
      -->
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="success" link @click="handleView(row)">查看</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button v-show="checkAuthByCode('')" type="danger" link @click="handleDelete(row)">删除</el-button>
          -->
          <el-button v-show="checkAuthByCode('PD0048')"
                     v-if="row.state === '0' && row.currentApproveUserId && row.currentApproveUserId.includes(getUserId())"
                     type="primary" link
                     @click="handleApprove(row)">审批</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogDetailVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="审批流程ID" prop="approveId">
          <el-input v-model="obj.approveId" type="number" placeholder="请输入审批流程ID" />
        </el-form-item>
        <el-form-item label="审批单编号" prop="approveOrderCode">
          <el-input v-model="obj.approveOrderCode" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="审批单名称" prop="approveOrderName">
          <el-input v-model="obj.approveOrderName" placeholder="请输入审批单名称，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="obj.state">
            <el-radio-button v-for="(item,index) in getEnumList('ApproveOrderState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提交人用户ID" prop="submitUserId">
          <User v-model="obj.submitUserId" keyName="id" keyShow="name" placeholder="" title="用户查询" />
        </el-form-item>
        <el-form-item label="当前审批节点号" prop="currentNo">
          <el-input v-model="obj.currentNo" type="number" placeholder="请输入当前审批节点号" />
        </el-form-item>
        <el-form-item label="当前审批人组织架构" prop="currentApproveOrgId">
          <Organization v-model="obj.currentApproveOrgId" keyName="id" keyShow="organizationName" placeholder="当前审批人组织架构" title="部门查询" />
        </el-form-item>
        <el-form-item label="当前审批人角色" prop="currentApproveRoleId">
          <Role v-model="obj.currentApproveRoleId" keyName="id" keyShow="roleName" placeholder="当前审批人角色" title="角色查询" />
        </el-form-item>
        <el-form-item label="当前审批人用户" prop="currentApproveUserId">
          <User v-model="obj.currentApproveUserId" keyName="id" keyShow="name" placeholder="" title="用户查询" />
        </el-form-item>
        <el-form-item label="下一节点审批组织架构" prop="nextApproveOrgId">
          <Organization v-model="obj.nextApproveOrgId" keyName="id" keyShow="organizationName" placeholder="下一节点审批组织架构" title="部门查询" />
        </el-form-item>
        <el-form-item label="下一节点审批角色" prop="currentApproveRoleId">
          <Role v-model="obj.currentApproveRoleId" keyName="id" keyShow="roleName" placeholder="下一节点审批角色" title="角色查询" />
        </el-form-item>
        <el-form-item label="下一节点审批人用户" prop="nextApproveUserId">
          <User v-model="obj.nextApproveUserId" keyName="id" keyShow="name" placeholder="" title="用户查询" />
        </el-form-item>
        <el-form-item label="审批结果" prop="approveResult">
          <el-input v-model="obj.approveResult" placeholder="请输入审批结果，最多输入20个字符" />
        </el-form-item>
        <el-form-item label="审批意见" prop="approveOpinion">
          <el-input v-model="obj.approveOpinion" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" />
        </el-form-item>
        <el-form-item label="业务单类型" prop="businessType">
          <el-radio-group v-model="obj.businessType">
            <el-radio-button v-for="(item,index) in getEnumList('ApproveOrderBusinessType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="业务单ID" prop="businessId">
          <el-input v-model="obj.businessId" type="number" placeholder="请输入业务单ID" />
        </el-form-item>
        <el-form-item label="业务单详情URL" prop="businessUrl">
          <el-input v-model="obj.businessUrl" placeholder="请输入业务单详情URL，最多输入500个字符" />
        </el-form-item>
        <el-form-item label="业务处理BeanClass" prop="businessClass">
          <el-input v-model="obj.businessClass" placeholder="请输入业务处理BeanClass，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogDetailVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import baseConfig from '@/mixins/baseConfig'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess, svc} from "@/config/common";
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import Role from "@/views/components/base/selectRole.vue";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  approveId: null, // 审批流程ID
  approveOrderCode: null, // 审批单编号
  approveOrderName: null, // 审批单名称
  submitUserId: null, // 提交人用户ID
  currentNo: null, //
  currentApproveOrgId: null,
  currentApproveRoleId: null,
  currentApproveUserId: null, // 当前审批人用户ID
  nextApproveOrgId: null,
  nextApproveRoleId: null,
  nextApproveUserId: null, // 下一节点审批人用户ID
  approveResult: null, // 审批结果
  approveOpinion: null, // 审批意见
  businessType: null, // 业务单类型
  businessId: null, // 业务单ID
  businessUrl: null, // 业务单详情URL
  businessClass: null, // 业务处理BeanClass
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'approveOrder_nocache',
  components: {Organization, Role, User, InputTagDialog},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogDetailVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      approve: {
        approveOrderId: null,
        approveResult: '',
        approveOpinion: '',
      },
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        approveId: null,
        approveOrderCode: null,
        approveOrderName: null,
        submitUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        currentNo: null,
        currentApproveOrgId: null,
        currentApproveRoleId: null,
        currentApproveUserId: null,
        nextApproveOrgId: null,
        nextApproveRoleId: null,
        nextApproveUserId: null,
        approveResult: null,
        businessType: null,
        businessId: null,
        businessUrl: null,
        businessClass: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        approveId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '审批流程ID', trigger: ['blur', 'change'] }],
        approveOrderCode: [{ required: true, validator: customValidator, min: 1, max: 100, label: '审批单编号', trigger: ['blur', 'change'] }],
        approveOrderName: [{ required: false, validator: customValidator, min: 0, max: 200, label: '审批单名称', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '审批单状态', trigger: ['blur', 'change'] }],
        submitUserId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '提交人用户ID', trigger: ['blur', 'change'] }],
        currentNo: [{ required: false, validator: customValidator, min: 0, max: 1, label: '当前节点编号', trigger: ['blur', 'change'] }],
        currentName: [{ required: false, validator: customValidator, min: 0, max: 100, label: '当前节点名称', trigger: ['blur', 'change'] }],
        currentApproveOrgId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '当前审批节点组织架构', trigger: ['blur', 'change'] }],
        currentApproveRoleId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '当前审批节点角色', trigger: ['blur', 'change'] }],
        currentApproveUserId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '当前审批节点用户', trigger: ['blur', 'change'] }],
        nextApproveOrgId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '下一节点审批节点组织架构', trigger: ['blur', 'change'] }],
        nextApproveRoleId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '下一节点审批节点角色', trigger: ['blur', 'change'] }],
        nextApproveUserId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '下一节点审批节点用户', trigger: ['blur', 'change'] }],
        approveResult: [{ required: false, validator: customValidator, min: 0, max: 20, label: '审批结果', trigger: ['blur', 'change'] }],
        approveOpinion: [{ required: false, validator: customValidator, min: 0, max: 0, label: '审批意见', trigger: ['blur', 'change'] }],
        businessType: [{ required: false, validator: customValidator, min: 0, max: 20, label: '业务单类型', trigger: ['blur', 'change'] }],
        businessId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '业务单ID', trigger: ['blur', 'change'] }],
        businessUrl: [{ required: false, validator: customValidator, min: 0, max: 500, label: '业务单详情URL', trigger: ['blur', 'change'] }],
        businessClass: [{ required: false, validator: customValidator, min: 0, max: 200, label: '业务处理BeanClass', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
      organizationList: initListStore().organizationList,
      roleList: initListStore().roleList,
      approveList: initListStore().approveList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    getListPageSize,
    getUserId,
    // async initList() {
    //   let p1 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(svc, '/role/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(svc, '/approve/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4])
    //   this.userList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.roleList = resArray[2]['records']
    //   this.approveList = resArray[3]['records']
    // },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/approve-order/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogDetailVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogDetailVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogDetailVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/approve-order/export', this.listQuery)
    },
    handleDelete(row) {
      this.$confirm('您确定删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        doDelete(this.svc, '/approve-order/' + row.id, {}).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogDetailVisible = false
        })
      })
    },
    handleApprove(row) {
      this.goTargetByName('approveOrderForm', {id: row.id})
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(this.svc, '/approve-order/modify', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogDetailVisible = false
        })
      } else if (this.dialogType === 'add') {
        doPost(this.svc, '/approve-order/add', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogDetailVisible = false
        })
      }
    },
  }
}
</script>
